package com.tanhua.admin.listener;

import com.tanhua.autoconfig.template.AliyunGreenTemplate;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.model.mongo.Movement;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 审核消息的监听器
 */
@Component
public class AuditListener {

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private AliyunGreenTemplate template;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.audit.queue"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.audit.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "audit.movement"
            )
    )
    public void log(String movementId) throws Exception {
        //1、根据id查询动态详情
        Movement movement = movementApi.findById(movementId);
        //2、获取文本内容和图片地址
        String text = movement.getTextContent();
        List<String> list = movement.getMedias();
        //3、调用工具类审核文本，审核图片
        Map<String, String> textScan = template.greenTextScan(text);
        String textSug = textScan.get("suggestion");
        Map<String, String> imageScan = template.imageScan(list);
        String imageSug = imageScan.get("suggestion");
        //4、根据结果，更新动态
        Integer state = 0;
        if("pass".equals(textSug) && "pass".equals(imageSug)) {
            //两个都通过
            state = 1; //通过
        }else if ("block".equals(textSug) || "block".equals(imageSug)) {
            state = 2; //通过
        }
        movementApi.updateState(movementId,state);
    }
}
